<template>
  <div class="order-expense-card">
    <!-- 费用顶部按钮 -->
    <div class="flex justify-between" style="margin-bottom: 10px">
      <a-checkbox class="custom-check" :model-value="isCheckAll" :indeterminate="isCheckAllIndeterminate" @change="handleChangeAll">
        选择/取消全部费项
      </a-checkbox>
    </div>
    <!-- 费用模块 -->
    <a-spin :loading="table.tableLoading" tip="加载中..." class="w-full">
      <card
        v-for="(item, index) in orderFeeList"
        :key="index"
        :showDivider="false"
        class="mb-4 w-full"
        toggle
        bordered
        :headerStyle="{ background: '#e8f3ff', padding: '10px 20px' }"
      >
        <template #title>
          <div class="order-expense-card__header">
            <span class="header-tit"
              >押金扣款抵扣租车金额：<span class="blue">{{ item.orderInfo?.allCount }}元</span></span
            >
            <span class="header-code" v-if="item.orderInfo?.orderCode"
              >押金抵扣结算订单号：<span class="header-value">{{ item.orderInfo?.orderCode }}</span></span
            >
            <span class="header-code">押金抵扣类型：<span class="header-value">租车费用</span></span>
          </div>
        </template>
        <table-index
          :table="item"
          :selectedKeys="selectedRowKeys[item.orderInfo?.id] || []"
          @selection-change="handleTableSelectChange($event, item.orderInfo.id)"
        >
          <template #payTypeNameList="{ record }">
            <p v-for="(pay, idx) in record.payTypeNameList" :key="idx">{{ pay }}</p>
          </template>
        </table-index>
      </card>
    </a-spin>
  </div>
</template>

<script setup>
  import { computed, reactive, ref } from 'vue'
  import { useTable } from '@/hooks/table'
  import { getCarFeeDetail } from '@/api/order/sOrder'
  import { decimalAddition } from '@/utils/index'

  const emits = defineEmits(['update:orderFeeList'])
  const props = defineProps({
    // 选中的费用列表
    orderFeeList: {
      type: Array,
      default: () => [],
    },
    // 押金信息
    depositInfo: {
      type: Object,
      default: () => ({}),
    },
    // 校验函数
    checkIsExceedFn: Function,
  })

  // 订单选中项
  const selectedRowKeys = reactive({})

  //租车费用
  const table = useTable({
    bordered: {
      wrapper: false,
      cell: true,
    },
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'itemName', fixed: 'left', width: 100 },
      { title: '总额', dataIndex: 'amount', unit: '元', width: 100 },
      { title: '实结', dataIndex: 'payAmount', unit: '元', width: 100 },
      {
        title: '未结',
        dataIndex: 'waitPayAmount',
        unit: '元',
        headerCellClass: 'tableCommonRed',
        bodyCellClass: 'tableCommonRed',
        width: 100,
      },
      { title: '收支类型', dataIndex: 'costTypeName', width: 100 },
      { title: '结算状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 100 },
      { title: '费用备注', dataIndex: 'remark', width: 160 },
    ],
  })

  // 订单费用列表
  const orderFeeList = computed(() => {
    let dataList = table.dataList
    if (!dataList.length) {
      return [{ ...table, dataList: [], pagination: null }]
    } else {
      return dataList.map((it) => ({
        ...table,
        dataList: it.feeDetailList || [],
        orderInfo: {
          ...it,
          allCount: it.allCount || 0,
        },
        pagination: null,
      }))
    }
  })

  /**
   * 校验当前操作是否超出剩余金额
   * @param operate 操作类型，tableCheck：表格选择，allCheck：全选
   * @param selectKeys 选中的id
   * @param orderId 操作的订单id
   * @returns {boolean}
   */
  const checkAmountIsExceed = (operate, selectKeys, orderId) => {
    // 合计金额
    let totalRentalFee = 0
    // 操作的是单个订单
    if (operate == 'tableCheck') {
      orderFeeList.value.forEach((order) => {
        const currOrderId = order.orderInfo.id
        // 当前操作的订单
        if (order.dataList) {
          // 传入了orderId，则当前订单按照传入的 selectKeys 进行汇总
          if (orderId && currOrderId == orderId) {
            // 选中的费项
            const checkedFees = order.dataList.filter((fee) => selectKeys.includes(fee.id))
            // 计算选中的费项的合计金额
            checkedFees.forEach((fee) => {
              totalRentalFee = decimalAddition(totalRentalFee, Number(fee.realAmount || 0))
            })
          } else {
            // 当前订单选中的费项
            const currSelectKeys = selectedRowKeys[currOrderId]
            if (currSelectKeys) {
              const checkedFees = order.dataList.filter((fee) => currSelectKeys.includes(fee.id))
              // 计算选中的费项的合计金额
              checkedFees.forEach((fee) => {
                totalRentalFee = decimalAddition(totalRentalFee, Number(fee.realAmount || 0))
              })
            }
          }
        }
      })
    } else {
      // 操作的是全选
      orderFeeList.value.forEach((order) => {
        if (order.dataList) {
          order.dataList.forEach((fee) => {
            totalRentalFee = decimalAddition(totalRentalFee, Number(fee.realAmount || 0))
          })
        }
      })
    }
    // 校验是否超出
    return props.checkIsExceedFn('rental', totalRentalFee)
  }

  // 全选
  const isCheckAll = ref(false)
  // 半选
  const isCheckAllIndeterminate = ref(false)
  // 全选切换事件
  const handleChangeAll = (val) => {
    // 选中
    if (val) {
      // 未超出
      if (!checkAmountIsExceed('allCheck')) {
        isCheckAll.value = true
        orderFeeList.value.forEach((item) => {
          selectedRowKeys[item.orderInfo.id] = item.dataList.map((d) => d.id)
        })
      }
    } else {
      isCheckAll.value = false
      // 非选中
      orderFeeList.value.forEach((item) => {
        selectedRowKeys[item.orderInfo.id] = []
      })
    }
    emitData()
  }

  // 费用选择事件
  const handleTableSelectChange = (selected, orderId) => {
    // 未超出
    if (!checkAmountIsExceed('tableCheck', selected, orderId)) {
      selectedRowKeys[orderId] = selected
      emitData()
    }
  }

  // 提交数据
  const emitData = () => {
    const tempFeeList = []
    // 费用数量
    let feeLength = 0
    orderFeeList.value.forEach((item) => {
      const orderId = item.orderInfo.id
      const orderCode = item.orderInfo.orderCode

      if (item.dataList && item.dataList.length > 0) {
        feeLength += item.dataList.length
        item.dataList.forEach((fee) => {
          // 如果当前订单有选中的费用，则添加到临时列表中
          const selectedFeeIds = selectedRowKeys[orderId]
          if (selectedFeeIds && selectedFeeIds.length > 0) {
            if (selectedFeeIds.includes(fee.id)) {
              tempFeeList.push({
                orderId,
                orderCode,
                cutPaymentAmount: fee.waitPayAmount,
                feeDetailId: fee.id,
                realAmount: fee.realAmount,
              })
            }
          }
        })
      }
    })
    // 更新全选半选状态
    isCheckAllIndeterminate.value = false
    isCheckAll.value = false
    if (tempFeeList.length > 0) {
      if (tempFeeList.length == feeLength) {
        isCheckAll.value = true
      } else {
        isCheckAllIndeterminate.value = true
      }
    }
    // 计算 allCount
    table.dataList.forEach((order) => {
      let sum = 0
      tempFeeList.forEach((feeItem) => {
        if (feeItem.orderId == order.id) {
          sum = decimalAddition(sum, feeItem.realAmount)
        }
      })

      order.allCount = sum
    })

    emits('update:orderFeeList', tempFeeList)
  }

  // 加载数据
  const loadData = () => {
    // 存在已有数据，则不请求
    if (table.dataList && table.dataList.length > 0) {
      return false
    }
    table.tableLoading = true
    const queryParam = {
      pageNumber: 1,
      pageSize: 1000,
      depositId: props.depositInfo.id,
    }
    getCarFeeDetail(queryParam)
      .then((res) => {
        table.tableLoading = false
        // 费项列表
        const list = res.result.data
        // costType 10 收款 20 付款
        list.forEach((order) => {
          const feeDetailList = order.feeDetailList
          if (feeDetailList && feeDetailList.length > 0) {
            feeDetailList.forEach((feeItem) => {
              const amount = feeItem.waitPayAmount
              // 收支类型
              const costType = feeItem.costType
              if (costType == 20) {
                // 转为负值
                feeItem.realAmount = amount == 0 ? 0 : -amount
              } else {
                feeItem.realAmount = amount
              }
            })
          }
        })
        table.dataList = list
      })
      .catch(() => {
        table.tableLoading = false
      })
  }

  // 清空状态
  const reset = () => {
    // 更新全选半选状态
    isCheckAllIndeterminate.value = false
    isCheckAll.value = false
    table.dataList = []

    for (var k in selectedRowKeys) {
      selectedRowKeys[k] = []
    }
  }

  defineExpose({
    loadData,
    reset,
  })
</script>

<style scoped lang="less">
  .w-full {
    width: 100%;
  }
  .custom-check {
    /deep/ .arco-checkbox-label {
      color: rgb(var(--primary-6));
    }
  }
  .order-expense-card__header {
    display: flex;
    justify-content: center;
    align-items: center;
    .title {
      font-weight: 600;
      font-size: 20px;
      color: #1d2129;
      margin-right: 20px;
    }
    .content {
      font-weight: 400;
      font-size: 14px;
      color: #4e5969;
      margin-right: 20px;
    }
  }
  .order-expense-card__desc {
    padding: 20px;
    .label {
      font-weight: 400;
      font-size: 14px;
      color: #4e5969;
      margin-right: 10px;
    }
    .value {
      font-weight: 400;
      font-size: 14px;
      color: #1d2129;
    }
  }
  .blue {
    color: #1890ff;
  }
  .header-tit {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 20px;
    color: #1d2129;
    margin-right: 20px;
  }
  .header-code {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #4e5969;
    margin-right: 20px;
  }
  .header-value {
    color: #1d2129;
  }
</style>
